<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="keywords" :label="$t('common.keywords')">
          <el-input
            v-model="queryParams.keywords"
            :placeholder="$t('solution.name')"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery">
            {{ $t("common.search") }}
          </el-button>
          <el-button icon="refresh" @click="handleResetQuery">{{ $t("common.reset") }}</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button
          v-hasPerm="'solution:add'"
          type="success"
          icon="plus"
          @click="handleOpenDialog()"
        >
          {{ $t("common.add") }}
        </el-button>
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="list"
        highlight-current-row
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column :label="$t('solution.name')" prop="title" />
        <el-table-column fixed="right" :label="$t('common.action')" width="220">
          <template #default="scope">
            <el-button
              v-hasPerm="'solution:edit'"
              type="primary"
              size="small"
              link
              icon="edit"
              @click="handleOpenDialog(scope.row.id)"
            >
              {{ t("common.edit") }}
            </el-button>
            <el-button
              v-hasPerm="'solution:delete'"
              type="danger"
              size="small"
              link
              icon="delete"
              @click="handleDelete(scope.row.id)"
            >
              {{ t("common.delete") }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="dialogWidth"
      @close="handleCloseDialog"
    >
      <el-form ref="roleFormRef" :model="formData" :rules="rules">
        <el-form-item :label="$t('solution.name')" prop="title">
          <el-input v-model="formData.title" :placeholder="$t('product.name')" />
        </el-form-item>
        <el-form-item :label="$t('common.sort')" prop="sort">
          <el-input v-model="formData.sort" placeholder="0" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">{{ t("common.confirm") }}</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
defineOptions({
  name: "Solution",
  inheritAttrs: false,
});

import SolutionAPI, { Form, Query, PageVO } from "@/api/solution/index";
const screenWidth = window.innerWidth;
const dialogWidth = screenWidth < 768 ? "90%" : "500px";
const queryFormRef = ref(ElForm);
const roleFormRef = ref(ElForm);

const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<Query>({
  pageNum: 1,
  pageSize: 10,
  keywords: "",
});

const list = ref<PageVO[]>();

const dialog = reactive({
  title: "",
  visible: false,
});

const formData = reactive<Form>({
  id: 0,
  title: "",
  sort: 0,
});

const rules = reactive({
  title: [{ required: true, message: t("common.plsInput") + t("product.name"), trigger: "blur" }],
});

function handleQuery() {
  loading.value = true;
  SolutionAPI.getList(queryParams)
    .then((data) => {
      list.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.deviceId);
}

function handleOpenDialog(customerId?: number) {
  dialog.visible = true;
  if (customerId) {
    dialog.title = t("common.edit");
    SolutionAPI.getFormData(customerId).then((data) => {
      Object.assign(formData, data);
      console.log(formData);
    });
  } else {
    dialog.title = t("common.add");
  }
}

function handleSubmit() {
  roleFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        SolutionAPI.update(formData)
          .then((res) => {
            if (res.data.code === 200) {
              ElMessage.success(res.data.message);
              handleCloseDialog();
              handleResetQuery();
            } else {
              ElMessage.error(res.data.message);
            }
          })
          .finally(() => (loading.value = false));
      } else {
        SolutionAPI.add(formData)
          .then((res) => {
            ElMessage.success(res.data.message);
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

function handleCloseDialog() {
  dialog.visible = false;

  roleFormRef.value.resetFields();
  roleFormRef.value.clearValidate();
  formData.id = 0;
  formData.title = "";
}

function handleDelete(customerId: number) {
  ElMessageBox.confirm(t("common.confirmDelete"), t("common.warning"), {
    confirmButtonText: t("common.confirm"),
    cancelButtonText: t("common.cancel"),
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      SolutionAPI.deleteByIds(customerId)
        .then((res) => {
          if (res.data.code === 200) {
            ElMessage.success(res.data.message);
            handleResetQuery();
          } else {
            ElMessage.error(res.data.message);
          }
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info(t("common.cancelDelete"));
    }
  );
}

onMounted(() => {
  handleQuery();
});
</script>
